<script setup lang="ts">
import { transformDataToKeys } from '@/utils';
import { generateNameToLevel } from '@/config/constant';
import { Message } from '@/instance';
import { modalMaterialUnitConfig } from './config/table-config';
import { saveSuccess } from '@/components/base-ui/base-table/hooks/useTableAction';
// import { searchConfig } from './config/search-config';
import {
    doGetMaterialUnit,
    doAddMaterialUnit,
    doEditMaterialUnit,
    doDelMaterialUnit
} from '@/api/base/materialsManagement';
import type { MaterialSetting } from '@/api/base/materialsManagement/model/type';

/**
 * 成功获取表格数据
 */
const handleLoadData = () => {
    const tableData: MaterialSetting[] = modalSlotRef.value.tableData;
    const AddOptionsLen = tableData.filter(item => item.edit).length;

    if (!AddOptionsLen) modalSlotRef.value.add();

    filterAndInsert(tableData);
};

/**
 * 三个固定分类，分别为“原材料、半成品、成品”这三个分类前期展示在物料分类设置弹窗中的1、2、3顺序中，置灰，不可勾选操作删除和编辑。
 */
const filterAndInsert = (data: MaterialSetting[]) => {
    const arr = ['成品', '半成品', '原材料'];

    arr.forEach((item: any) => {
        const index = data.findIndex(function (obj) {
            return obj.classificationName === item;
        });

        if (index > -1) {
            const element = data.splice(index, 1)[0];
            element.disabled = true;
            data.unshift(element);
        }
    });
};

// 禁用表格操作权限
const handleDisabled = (row: MaterialSetting) => row.disabled!;

/**
 * 新增/编辑
 */
const { modalOk, modalSlotRef, getMaxHeight } = useModal();

// const { search } = useParams(modalSlotRef);

/**
 * 物料分类设置行内编辑保存
 */
const { rowEdit } = useEditRow(modalSlotRef, doEditMaterialUnit);
const handleMaterialChange = async (row: any, oldRow: any) => {
    try {
        let data = transformDataToKeys<any>(row, [
            'id',
            'productUnit',
            'purchaseUnit',
            'productPurchaseUnitRatio',
            'productUnits',
            'purchaseUnits'
        ]);
        const productUnits = data['productUnits'] === null ? 1 : data['productUnits'];
        const purchaseUnits = data['purchaseUnits'] === null ? 1 : data['purchaseUnits'];
        //数据生产单位:采购单位都填写给后端传递的参数合并
        if (row['productUnits'] === null && row['purchaseUnits'] === null) {
            row['productPurchaseUnitRatio'] = '';
            data['productPurchaseUnitRatio'] = '';
        } else {
            row['productPurchaseUnitRatio'] = productUnits + ':' + purchaseUnits;
            data['productPurchaseUnitRatio'] = productUnits + ':' + purchaseUnits;
        }
        // 采购单位的状态
        if ((row.purchaseUnit && row.productUnits !== '') || row.purchaseUnits !== '') {
            const res = await rowEdit<MaterialSetting>(data, oldRow);
            if (!res) return;
            // 将最新数据替换备份数据
            saveSuccess(row, oldRow, modalSlotRef);
            modalSlotRef.value?.getData?.();
        } else if (!row.purchaseUnit) {
            const res = await rowEdit<MaterialSetting>(data, oldRow);
            if (!res) return;
            // 将最新数据替换备份数据
            saveSuccess(row, oldRow, modalSlotRef);
            modalSlotRef.value?.getData?.();
        } else {
            Message.error('生产单位 : 采购单位不能为空1');
        }
    } catch (error) {
        console.log('error', error);
    }
};

// 删除数据
const selectIds = ref<number[]>([]);
const handleSelection = (list: MaterialSetting[]) => {
    selectIds.value = list.map((item: MaterialSetting) => item.id!);
};

const { rowDel } = useDelRow(modalSlotRef, selectIds, doDelMaterialUnit);

/**
 * 物料分类确认新增
 */
const getData = async () => {
    let data: MaterialSetting[] = modalSlotRef.value.getSaveData();
    const editTableData = modalSlotRef.value.tableData.filter(
        (item: anyObj) => item.edit && item.unAction
    );

    data = data.map((item, index) => {
        //判断数据生产单位:采购单位存在这个参数给值
        const productUnits = editTableData[index].productUnits
            ? editTableData[index].productUnits
            : '';
        const purchaseUnits = editTableData[index].purchaseUnits
            ? editTableData[index].purchaseUnits
            : '';
        let strUnit;
        //数据生产单位:采购单位都填写给后端传递的参数合并
        if (productUnits !== '' && purchaseUnits !== '') {
            strUnit = productUnits + ':' + purchaseUnits;
        }
        //数据生产单位:采购单位其他任何情况填写给后端传递的参数合并
        else {
            strUnit = '';
        }
        return {
            ...item,
            productPurchaseUnitRatio: strUnit
        };
    });
    const tableData = modalSlotRef.value.tableData.filter((item: anyObj) => !item.edit);
    const saveData: MaterialSetting[] = modalSlotRef.value.getSaveData();
    //加新增单位是否重复
    const uniques = hasIdenticalElement(editTableData);
    //判断新增单位与有的数据是否相等
    const result = hasSimilarElements(saveData, tableData);
    //加校验规则
    let errMsg = '';
    let rules = true;
    editTableData.forEach((item: anyObj, index: number) => {
        if (item.purchaseUnit && !item.productUnits && !item.purchaseUnits) {
            rules = false;
            errMsg = `第${index + 1}行新增生产单位 : 采购单位不能为空`;
        } else if (
            (item.purchaseUnit && !item.productUnits) ||
            (item.purchaseUnit && !item.purchaseUnits)
        ) {
            rules = false;
            errMsg = `第${index + 1}行新增生产单位 : 采购单位填写完整`;
        }
    });
    //判断新增单位数据校验提示
    if (rules) {
        //新增单位是否重复
        if (uniques) {
            Message.error('新增物料单位存在重复');
        } else {
            //判断新增单位是否存在
            if (result) {
                Message.error('新增物料单位已存在');
            } else {
                await doAddMaterialUnit(data);
                Message.success('操作成功！');
                modalSlotRef.value?.getData?.();
            }
        }
    } else {
        Message.error(errMsg);
    }
};

/**
 * 新增物料单位找相同元素
 */
const objectsAreEqual = (obj1: any, obj2: any) => {
    let keys1: any[] = [];
    let keys2: any[] = [];
    if (obj1.idte__mp) {
        keys1 = Object.keys(obj1).filter(key => key !== 'id' && key !== 'idte__mp');
        keys2 = Object.keys(obj2).filter(key => key !== 'id' && key !== 'idte__mp');
    } else {
        keys1 = Object.keys(obj1).filter(key => key !== 'id');
        keys2 = Object.keys(obj2).filter(key => key !== 'id');
    }
    if (keys1.length !== keys2.length) {
        return false;
    }

    for (let key of keys1) {
        if (obj1[key] !== obj2[key]) {
            return false;
        }
    }

    return true;
};

/**
 * 新增物料单位找已存在数据
 */
const hasSimilarElements = (arr: any[], arr1: any[]) => {
    for (let item of arr) {
        for (let item1 of arr1) {
            if (objectsAreEqual(item, item1)) {
                return true; // 找到匹配的元素，立即返回 true
            }
        }
    }

    return false; // 遍历完两个数组，没有找到匹配的元素
};
/**
 * 新增物料单位找相同元素
 */
const hasIdenticalElement = (arr: any[]) => {
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (objectsAreEqual(arr[i], arr[j])) {
                return true; // 找到完全相同的元素
            }
        }
    }
    return false; // 没有找到完全相同的元素
};
const handleOk = () => {
    modalOk(getData);
};

const handleSelectDisabled = (row: MaterialSetting) => {
    return !row.disabled;
};

/**
 * 物料单位编辑
 */
const edit = (row: anyObj) => {
    //判断生产单位:采购单位字段里面是否存在:
    const boor = row.productPurchaseUnitRatio?.includes(':');
    //判断生产单位:采购单位字段是否为undefined
    if (!row.productPurchaseUnitRatio) {
        row.productUnits = null;
        row.purchaseUnits = null;
    }
    //生产单位:采购单位字段存在:分别把数据赋值给生产单位:采购单位
    else if (boor) {
        let unit = row.productPurchaseUnitRatio?.split(':');
        row.productUnits = parseInt(unit[0]);
        row.purchaseUnits = parseInt(unit[1]);
    }
};
defineExpose({
    handleOk
});
</script>

<template>
    <div style="padding: 0 10px">
        <base-table
            :id="generateNameToLevel('2')"
            ref="modalSlotRef"
            :table-attr="{ showOverflowTooltip: false }"
            valid-popover-position="left"
            :getDataFn="doGetMaterialUnit"
            :max-height="getMaxHeight"
            :add-table-row="true"
            :cell-edit="true"
            :tableConfig="modalMaterialUnitConfig"
            :modal-mode="true"
            :editDisabledFn="handleDisabled"
            :delDisabledFn="handleDisabled"
            :selectable="handleSelectDisabled"
            @change="handleMaterialChange"
            @selectionChange="handleSelection"
            @del="rowDel"
            @edit="edit"
            @load="handleLoadData"
        >
            <template #productPurchaseUnitRatio="{ row }">
                <div v-if="row.edit" style="display: flex">
                    <el-input-number
                        v-model="row.productUnits"
                        :min="1"
                        :max="9999999999"
                        :precision="0"
                        :controls="false"
                    />
                    <span style="margin: 0 5px">:</span>
                    <el-input-number
                        v-model="row.purchaseUnits"
                        :min="1"
                        :max="9999999999"
                        :precision="0"
                        :controls="false"
                    />
                </div>
                <div v-else>{{ row.productPurchaseUnitRatio }}</div>
            </template>
        </base-table>
    </div>
</template>

<style lang="scss" scoped></style>
